package in.muton.edushare.jobs;

import java.util.Date;

import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.SimpleTrigger;
import org.quartz.Trigger;
import org.quartz.TriggerUtils;

public class EduShareJobScheduler {

	private static EduShareJobScheduler eduShareScheduler;
	private Scheduler scheduler;

	private EduShareJobScheduler() {
	}

	public static EduShareJobScheduler getInstance() {
		if (eduShareScheduler == null) {
			eduShareScheduler = new EduShareJobScheduler();
		}
		return eduShareScheduler;
	}

	public void start() throws SchedulerException {
		SchedulerFactory schFact = new org.quartz.impl.StdSchedulerFactory();
		this.scheduler = schFact.getScheduler();
		scheduler.start();
		loadJobs();
	}

	/**
	 * Add your jobs and triggers here, this will be loaded at start-up
	 * 
	 * @throws SchedulerException
	 */
	private void loadJobs() throws SchedulerException {
		addSingleJob("StartupAssignemntUpdateJob", AssignemntUpdaterJob.class);
		addSingleJob("StartupSemesterElectiveJob", ElectiveAssignJob.class);
		addSingleJob("StartupSemesterChangeJob", SemesterChangeJob.class); 
		
		addDailyJob("AssignemntUpdateJob", AssignemntUpdaterJob.class, 0, 0);
		addDailyJob("SemesterElectiveJob", ElectiveAssignJob.class, 0, 0);
		addDailyJob("SemesterChangeJob", SemesterChangeJob.class, 0, 0);
		addDailyJob("PollUpdateJob", PollUpdater.class, 23, 58);
		addDailyJob("CourseCodeReminderJob", CourseInfoReminderJob.class, 23, 58);
	}

	private void addDailyJob(String jobName, Class<? extends EduShareJob> jobClass,
			int hours, int mins) throws SchedulerException {
		JobDetail job = new JobDetail(jobName, Scheduler.DEFAULT_GROUP,
				jobClass);
		Trigger trigger = TriggerUtils.makeDailyTrigger(hours, mins);
		trigger.setStartTime(new Date());
		trigger.setName(jobName);
		this.scheduler.scheduleJob(job, trigger);

	}

	private void addSingleJob(String jobName, Class<? extends EduShareJob> jobClass)
			throws SchedulerException {
		JobDetail job = new JobDetail(jobName,
				Scheduler.DEFAULT_GROUP, jobClass);
		Trigger trigger = new SimpleTrigger(jobName,
				Scheduler.DEFAULT_GROUP, new Date());
		this.scheduler.scheduleJob(job, trigger);
	}

}
